﻿namespace eslib.FileManageLib
{
    public static class DirTool
    {
        /// <summary>
        /// 将src目录下所有文件和目录复制到dest目录下
        /// 不包括src和desc本身
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dest"></param>
        public static void DirectoryCopy(string src, string dest)
        {
            //复制文件
            string[] files = Directory.GetFiles(src);
            foreach (var file in files)
            {
                string fname = Path.GetFileName(file);
                fname = Path.Combine(dest, fname);
                File.Copy(file, fname, true);       //覆盖
            }

            //复制目录
            string[] dirs = Directory.GetDirectories(src);
            foreach (var dir in dirs)
            {
                //创建目录
                string dname = Path.GetFileName(dir);
                dname = Path.Combine(dest, dname);
                CreateDir(dname);

                //如果目录还包括文件或目录，则递归
                if (hasSub(dir))
                {
                    DirectoryCopy(dir, dname);
                }
            }
        }

        /// <summary>
        /// 创建不存在的目录
        /// </summary>
        /// <param name="dir"></param>
        public static void CreateDir(string dir)
        {
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
        }


        static bool hasSub(string path)
        {
            int flen = Directory.GetFiles(path).Length;
            int dlen = Directory.GetDirectories(path).Length;
            return (flen + dlen > 0);
        }
    }
}